<?php


namespace app\zyhsapi\controller\v1;


use app\common\cachemodel\ZlcrAstr;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\lib\OrdersLib;
use app\zyhsapi\model\ZyhsAstrTasks;
use app\zyhsapi\model\ZyhsConsultChatRtcRecord;
use app\zyhsapi\model\ZyhsOrders;
use app\zyhsapi\model\ZyhsQuestionUserView;
use app\zyhsapi\model\ZyhsUser;
use app\zyhsapi\model\ZyhsUserAccount;
use app\zyhsapi\model\ZyhsUserAccountRecord;
use app\zyhsapi\model\ZyhsUserAddQuestion;
use app\zyhsapi\model\ZyhsUserQuestion;
use think\response\Json;

/**
 * 2.5.0准币控制器
 * Class Coin
 * @package app\api\controller\v21
 */
class Coin extends ZyhsAuth
{
    protected $msg;

    /**
     * 准币明细
     * @return Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function coinDetail()
    {
        $user_coin_detail = (new ZyhsUserAccountRecord())->getUserCoinDetailListFromCache($this->user['id']);
        $zlcrAstrModel = new ZlcrAstr();
        $zyhsConsultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        // 流水类型1=>校准生辰 2=>日运 3=>月运 4=>年运 5=>幸运之城 6=>教学视频 7=>本命预测 8会员购买 9准币充值 10许愿充值
        $data = [];
        foreach ($user_coin_detail['data'] as $datum)
        {
            $datum['order_type'] = (int)$datum['order_type'];
            $datum['consumer_type'] = (int)$datum['consumer_type'];
            $extend = json_decode($datum['extend'], true);
            $liveName = $extend['live_info']['name'] ?? '';
            $target = 'local';
            $link = '';
            $type = 0;

            switch ($datum['order_type'])
            {
                case 9: //准币
                    if (Util::IsIos())
                    {
                        $title = 'Z币';
                    } else
                    {
                        $title = '准币';
                    }
                    break;
                case 100: //连麦咨询
                    $extend = json_decode($datum['extend'], true);
                    if (isset($extend['rtc_id']))
                    {
                        $rtcInfo = $zyhsConsultChatRtcRecordModel->getInfoById($extend['rtc_id']);
                        $astrInfo = $zlcrAstrModel->getInfoById($rtcInfo['astr_id']);
                        $nickname = $astrInfo['nickname'];
                        $link = "rtc_consult_detail?id={$rtcInfo['chat_detail_id']}&need_auth=2";
                        $type = 1;
                    } else
                    {
                        $nickname = '';
                    }
                    $title = "连线咨询（{$nickname}）";
                    break;
                case 101: //问答
                    $type = 1;
                    $orders = (new ZyhsOrders())->getInfoById($datum['order_id']);
                    $questionType = (new ZyhsUserQuestion())->getQuestionType($orders['gid']);
                    $des = $datum['consumer_type'] === 4 ? '退款' : '';
                    switch ($questionType['type'])
                    {
                        case 1://蹭看
                            $taskId = (new ZyhsQuestionUserView())->where('order_num', $datum['order_id'])->value('task_id');
                            $qid = (new ZyhsAstrTasks())->getInfoById($taskId, ['qid'])['qid'];
                            $title = '问答蹭看' . $des;
                            break;
                        case 2://追问
                            $taskId = (new ZyhsUserAddQuestion())->where('order_num', $datum['order_id'])->value('task_id');
                            $qid = (new ZyhsAstrTasks())->getInfoById($taskId, ['qid'])['qid'];
                            $title = '问答追问' . $des;
                            switch ($questionType['sec'])
                            {
                                case 1:
                                    $title .= '（星盘）';//星盘
                                    break;
                                case 2:
                                    $title .= '（骰子）';//骰子
                                    break;
                                case 3:
                                    $title .= '（幸运卡牌）';//塔罗
                                    break;
                            }
                            break;
                        case 3://问答
                            $title = '悬赏问答' . $des;
                            $qid = (new ZyhsUserQuestion())->where('order_num', $datum['order_id'])->value('id');
                            $questionConfig = config('zyhs_question');
                            switch ($questionType['sec'])
                            {
                                case 1:
                                    $title .= "（星盘-{$questionConfig['info'][$datum['gid']]['consult_num']}人）";//星盘
                                    break;
                                case 2:
                                    $title .= "（骰子{$questionConfig['info'][$datum['gid']]['consult_num']}人）";//骰子
                                    break;
                                case 3:
                                    $title .= "（幸运卡牌{$questionConfig['info'][$datum['gid']]['consult_num']}人）";//塔罗
                                    break;
                            }
                            break;
                        default:
                            $title = '';
                            $qid = '';
                    }
                    $link = "question_detail?qid={$qid}&need_auth=0";
                    break;
                case 110:
                    $title = '提前发送星盘';
                    break;
                default :
                    $title = '商品';
                    break;
            }

            if ($datum['consumer_type'] === 1)
            {
                $type_des = '已到账';
                $title = $title ? $title . '充值' : '';
                $price = $datum['coin_num'] ? '+' . $datum['coin_num'] : 0;
            } elseif ($datum['consumer_type'] === 2)
            {
                $type_des = '已支付';
                $price = $datum['coin_num'] ? '-' . $datum['coin_num'] : 0;
                if (!in_array($datum['order_type'], [100, 101, 110], true))
                {
                    $title = $title ? '购买' . $title : '';
                }
            } elseif ($datum['consumer_type'] === 3)
            {
                $type_des = '已赠送';
                $title = $title ? '赠送' . $title : '';
                $price = $datum['coin_num'] ? '+' . $datum['coin_num'] : 0;
            } elseif ($datum['consumer_type'] === 4)
            {
                $type_des = '已退款';
                $price = $datum['coin_num'] ? '+' . $datum['coin_num'] : 0;
                if ($datum['order_type'] !== 101)
                {
                    $title = $title ? $title . '退款' : '';
                }
            } elseif ($datum['consumer_type'] === 5)
            {
                $type_des = '已打赏';
                $title = "打赏（{$liveName}）";
                $price = $datum['coin_num'] ? '-' . $datum['coin_num'] : 0;
            } elseif ($datum['consumer_type'] === 6)
            {
                $type_des = '已退款';
                $title = "充值退款";
                $price = $datum['coin_num'] ? '-' . $datum['coin_num'] : 0;
            } else
            {
                $price = $datum['coin_num'];
            }

            $data[] = [
                'id' => $datum['id'],
                'title' => $title,
                'create_time' => date('Y-m-d H:i:s', $datum['create_time']),
                'price' => $price,
                'type_des' => $type_des,
                'target' => $target,
                'link' => $link,
                'type' => $type,
                'order_id' => $datum['order_id'],
            ];
        }
        $user_coin_detail['data'] = $data;
        return show(config('code.success'), '获取成功', $user_coin_detail);
    }

    /**
     * 准币商品
     * @return Json
     * @throws \Exception
     */
    public function coinGoods()
    {
        $arr = [
            'goods_data' => [],
            'coin_num' => (new ZyhsUserAccount())->getCoinNum($this->user['id']),
            'nickname' => $this->user['nickname'],
            'avatar' => $this->user['avatar'],
        ];
        $goods = (new ZyhsUserAccount())->coinGoods(Util::IsIos(), $this->user);
        foreach ($goods as $k => $good)
        {
            if ($arr['coin_num'] <= 0 && $k === 44)
            {
                continue;
            }
            $arr['goods_data'][] = [
                'num' => $good['coin_num'],
                'price' => (string)$good['now_prize'],
                'gid' => (int)$good['id'],
                'apple_id' => $good['apple_id'] ?? '',
            ];
        }
        return show(config('code.success'), '获取成功', $arr);
    }

    /**
     * 充值准币
     * @return Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function coinRecharge()
    {
        $gid = input('param.gid/d', 0);
        $trade_type = input('param.trade_type/d', 0);
        $ryDeviceId = input('param.ry_device_id/s', '');
        (new ZyhsUser())->updateUserinfo(['id' => $this->user['id']], ['regid' => $ryDeviceId]);
        //检测参数并获取商品信息
        $goods = $this->CheckRechargeParam($gid, $trade_type);
        //获取订单描述语和订单编号
        $order_type_des = OrdersLib::createOrderId();
        if ($trade_type === 9)
        {
            $account['account'] = '';
        } else
        {
            $account = OrdersLib::getOrderAccountType($order_type_des['order_id'], $trade_type);
        }
        //获取用户余额信息
        $user_coin = OrdersLib::getCoinNum($this->user['id']);
        $insertData = [
            'status' => 0,
            'account' => $account['account'],
            'uid' => $this->user['id'],
            'consumer_type' => 1,
            'order_type' => 9,
            'gid' => $gid,
            'total_amount' => $goods['received_price'] ?? $goods['now_prize'],//实际收入
            'pay_price' => $goods['now_prize'],//用户支付
            'coin_num' => $goods['coin_num'],
            'balance' => $goods['coin_num'] + $user_coin,
            'order_id' => $order_type_des['order_id'],
            'trade_type' => $trade_type,
            'create_time' => time(),
            'transaction_id' => '',
        ];
        //增加准币明细记录
        $oid = (new ZyhsUserAccountRecord())->SaveData($this->user['id'], $insertData);
        if ($oid)
        {
            //支付订单
            $arr = OrdersLib::unifyPayOrder([
                'trade_type' => $trade_type,
                'total_amount' => $goods['now_prize'],
                'pay_des' => $order_type_des['pay_des'],
                'order_id' => $order_type_des['order_id'],
                'openid' => '',
                'callback_url' => '',
                'order_type' => 9,
            ], 1);

            $arr['data']['skuId'] = $goods['apple_id'] ?? '';
            return show(config('code.success'), '充值下单成功', $arr['data']);
        }
        return show(config('code.error'), '充值下单失败');
    }

    /**
     * 检测充值参数,并获取商品信息
     * @param $gid
     * @param $trade_type
     * @return mixed
     * @throws ApiException
     */
    private function CheckRechargeParam($gid, $trade_type)
    {
        $goods = (new ZyhsUserAccount())->coinGoods(Util::IsIos(), $this->user);
        //1=>支付宝 2=》微信 4=》准币 9=》苹果
        if (!in_array($trade_type, [1, 2, 9], true))
        {
            throw new ApiException('支付方式未知');
        }
        //检测准币商品
        if (!isset($goods[$gid]))
        {
            throw new ApiException('商品未知');
        }
        return $goods[$gid];
    }
}
